package celiasoft.itasalib.query.resultparser;

import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.result.QueryResult;
import celiasoft.itasalib.query.result.QueryResultError;

public class QueryResultParserError {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.QueryResultParserError";


	public QueryResult parse(Document doc) {

		if(checkStatus(doc)){
			return null;
		}
		
		String errCode = DomHandler.getValue(doc,"code");
		String errMsg = DomHandler.getValue(doc,"message");
		
		if(errCode == null || errMsg == null){
			return  null;
		}
		
		QueryResultError qre = new QueryResultError(Integer.parseInt(errCode), errMsg);
		
		return new QueryResult(qre);
	}
	
	public QueryResult parse(TagNode root) {
		return null;
	}

	protected final boolean checkStatus(Document doc){
		
		
		//Log.d(TAG, "first node name: " + doc.getFirstChild().getFirstChild().getFirstChild().getNodeName());
		NodeList nl = doc.getElementsByTagName("status");
		
		if(nl == null){
			return false;
		}
		
		for(int i = 0; i < nl.getLength(); i++){
			String value = DomHandler.getElementValue(nl.item(i));
			if("success".compareToIgnoreCase(value) == 0){
				return  true;
			}
			
		}
		
		return false;
	}

}
